
import calendar_ex.Appointment;
import calendar_ex.CalendarDate;
import calendar_ex.CalendarTime;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.text.BadLocationException;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Marco
 */
public class AddEventPanel extends ObservingJPanel {

    protected CalendarController controller;
    private JLabel dateLabel;
    private JLabel startLabel;
    private JLabel endLabel;
    private JLabel nameLabel;
    private JLabel tagsLabel;
    private JLabel locationLabel;
    private JLabel reminderLabel;
    private JLabel repeatEveryLabel;
    private JLabel finishAfterLabel;
    private JLabel descriptionLabel;
    protected JComboBox hour;
    protected JComboBox minutes;
    protected JComboBox endHour;
    protected JComboBox endMinutes;
    protected JTextField nameInput;
    protected JTextField tagsInput;
    protected JTextField locationInput;
    protected JComboBox reminderInput;
    protected JComboBox repeatEveryInput;
    protected JTextField descriptionInput;
    protected JTextField dateInput;
    protected JTextField finishAfterInput;
    private JButton save;
    private JPanel dateInputPanel;
    private JPanel endDateInputPanel;
    protected JPanel inputForm;
    protected Appointment currentAppointment;
    protected JButton deleteButton;
    static int idCount = 0;

    private CalendarDate processDate(String date) {
        int verifyDay;
        int verifyMonth;
        int verifyYear;
        try {
            verifyDay = Integer.parseInt(date.substring(0, 2));
            verifyMonth = Integer.parseInt(date.substring(3, 5));
            verifyYear = Integer.parseInt(date.substring(6));
        } catch (Exception e) {
            return null;
        }
        if (verifyMonth == 0 || verifyMonth == 0 || verifyMonth == 0) {
            return null;
        }

        if (date.charAt(2) != '-' && date.charAt(5) != '-') {
            return null;
        }
        if ((verifyMonth == 4 || verifyMonth == 6 || verifyMonth == 9 || verifyMonth == 11) && verifyDay > 30) {

            return null;

        }
        if (verifyDay > 31) {
            return null;
        }
        if (verifyMonth == 2 && verifyDay > 28) {
            return null;
        }
        if (verifyMonth < 1 || verifyMonth > 12) {
            return null;
        }
        if (date.substring(6).length() != 4) {
            return null;
        }
        return new CalendarDate(verifyDay, verifyMonth, verifyYear);
    }

    private void createStartTimePanel(Appointment a) {
        dateInputPanel = new JPanel();
        dateInputPanel.setLayout(new BoxLayout(dateInputPanel, BoxLayout.X_AXIS));


        hour = new JComboBox(CalendarController.hoursList);
        minutes = new JComboBox(CalendarController.minutesList);
        if (a != null) {
            if (a.start_time.hr < 10) {
                hour.setSelectedItem("0" + a.start_time.hr);
            } else {
                hour.setSelectedItem("" + a.start_time.hr);
            }
            if (a.start_time.min < 10) {
                minutes.setSelectedItem("0" + a.start_time.min);
            } else {
                minutes.setSelectedItem("" + a.start_time.min);
            }



        }

        dateInputPanel.add(hour);
        dateInputPanel.add(minutes);
    }

    private void createEndTimePanel(Appointment a) {
        endDateInputPanel = new JPanel();
        endDateInputPanel = new JPanel();
        endDateInputPanel.setLayout(new BoxLayout(endDateInputPanel, BoxLayout.X_AXIS));


        endHour = new JComboBox(CalendarController.hoursList);
        endMinutes = new JComboBox(CalendarController.minutesList);

        if (a != null) {
            if (a.end_time.hr < 10) {
                endHour.setSelectedItem("0" + a.end_time.hr);
            } else {
                endHour.setSelectedItem("" + a.end_time.hr);
            }
            if (a.end_time.min < 10) {
                endMinutes.setSelectedItem("0" + a.end_time.min);
            } else {
                endMinutes.setSelectedItem("" + a.end_time.min);
            }



        }


        endDateInputPanel.add(endHour);
        endDateInputPanel.add(endMinutes);

    }

    private void createInputForm(Appointment a) {

        this.createEndTimePanel(a);
        this.createStartTimePanel(a);

        //this.createFinishAfterDatePanel();
        inputForm = new JPanel();
        inputForm.setLayout(new GridLayout(0, 2));

        dateLabel = new JLabel("Date");
        startLabel = (new JLabel("Start time"));
        endLabel = new JLabel("End time");
        nameLabel = (new JLabel("Name"));
        tagsLabel = (new JLabel("Tags"));
        locationLabel = (new JLabel("Location"));
        reminderLabel = (new JLabel("Reminder"));
        repeatEveryLabel = (new JLabel("Repeat every"));
        finishAfterLabel = (new JLabel("Finish after"));
        descriptionLabel = (new JLabel("Description"));

        if (a != null) {
            nameInput = new JTextField(a.name);
            dateInput = new JTextField(a.date.toString());
            if(a.getTags() != null)
            tagsInput = new JTextField(a.getTags().toString());
           
            locationInput = new JTextField(a.location);
            reminderInput = new JComboBox(CalendarController.minutesList);
            repeatEveryInput = new JComboBox(CalendarController.repeatEveryOptions);
            descriptionInput = new JTextField(a.description);
            if(a.finishDate != null)
            finishAfterInput = new JTextField(a.finishDate.toString());
            else{
                finishAfterInput = new JTextField();
            }

            String reminderStr;
            if (a.reminder < 10) {
                reminderStr = "0" + Integer.toString(a.reminder);
            } else {
                reminderStr = Integer.toString(a.reminder);
            }

            reminderInput.setSelectedItem(reminderStr);
            repeatEveryInput.setSelectedItem(a.recur.toString());
        } else {
            nameInput = new JTextField();
            dateInput = new JTextField(this.controller.calendarModel.getViewDate().toString());
            tagsInput = new JTextField();
            locationInput = new JTextField();
            reminderInput = new JComboBox(CalendarController.minutesList);
            repeatEveryInput = new JComboBox(CalendarController.repeatEveryOptions);
            descriptionInput = new JTextField();
            finishAfterInput = new JTextField();

        }





        

        inputForm.add(dateLabel);
        inputForm.add(dateInput);
        inputForm.add(startLabel);
        inputForm.add(dateInputPanel);
        inputForm.add(endLabel);
        inputForm.add(endDateInputPanel);
        inputForm.add(nameLabel);
        inputForm.add(nameInput);
        inputForm.add(tagsLabel);
        inputForm.add(tagsInput);
        inputForm.add(locationLabel);
        inputForm.add(locationInput);
        inputForm.add(reminderLabel);
        inputForm.add(reminderInput);
        inputForm.add(repeatEveryLabel);
        inputForm.add(repeatEveryInput);
        inputForm.add(finishAfterLabel);
        inputForm.add(finishAfterInput);
        inputForm.add(descriptionLabel);
        inputForm.add(descriptionInput);



    }

    public AddEventPanel(Appointment a, CalendarController calControl) {

        this.controller = calControl;

        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        //used for testing
        //CalendarTime endTime = new CalendarTime(12, 10);
        //CalendarTime startTime = new CalendarTime(10, 10);
        //CalendarDate date = new CalendarDate(11, 11, 2011);
        //CalendarDate endDate = new CalendarDate(11, 12, 2011);
        //ArrayList<String> tags = new ArrayList<String>();
        //tags.add("Marco");
        //Appointment x = new Appointment("test event", endDate, date, endTime, startTime, "description", "glasgow", tags, Appointment.Recurrence.WEEKLY, 5, null);
        this.currentAppointment = a;
        this.createInputForm(a);
        save = new JButton("Save");
        save.setAlignmentX(save.CENTER_ALIGNMENT);
        save.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                if (currentAppointment != null) {

                    controller.calendarModel.removeAppointment(currentAppointment);
                }

                CalendarTime endTime = new CalendarTime(Integer.parseInt(endHour.getSelectedItem().toString()), Integer.parseInt(endMinutes.getSelectedItem().toString()));
                CalendarTime startTime = new CalendarTime(Integer.parseInt(hour.getSelectedItem().toString()), Integer.parseInt(minutes.getSelectedItem().toString()));
                CalendarDate date = processDate(dateInput.getText());
                CalendarDate endDate = processDate(finishAfterInput.getText());

                if (nameInput.getText().equalsIgnoreCase("")) {
                    JOptionPane.showMessageDialog(inputForm, "Please name your event", "Create Name", JOptionPane.ERROR_MESSAGE);
                    return;
                }


                 if (endDate == null) {
                    if (!finishAfterInput.getText().equalsIgnoreCase("")) {
                        JOptionPane.showMessageDialog(inputForm, "Invalid finish after date.\n The date should be\n of the format:\n DD-MM-YYYY", "Invalid Date", JOptionPane.ERROR_MESSAGE);
                    return;
                    }
                }


                if (CalendarTime.compare(startTime, endTime) == -1) {
                    JOptionPane.showMessageDialog(inputForm, "Finish time must be after\n start time", "Time Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                ArrayList<String> tags = new ArrayList<String>();

                int reminder = Integer.parseInt(reminderInput.getSelectedItem().toString());
                String tag = tagsInput.getText();
                ArrayList<String> tagsList = new ArrayList<String>();
                tags.add(tag);
                Appointment b = new Appointment(nameInput.getText(), endDate, date, startTime, endTime, descriptionInput.getText(), locationInput.getText(), tagsList, Appointment.Recurrence.valueOf(repeatEveryInput.getSelectedItem().toString()), reminder);
                System.out.println("app made test");
                controller.calendarModel.addAppointment(b);
                currentAppointment = b;
                JOptionPane.showMessageDialog(inputForm, "Saved.Please press back", "Saved", JOptionPane.OK_OPTION);

                //controller.calendarModel.printCalendar();



            }
        });

        this.add(inputForm);
        this.add(save);
        if (currentAppointment != null) {
            deleteButton = new JButton("Delete");
            this.add(deleteButton);
            deleteButton.setAlignmentX(deleteButton.CENTER_ALIGNMENT);
            deleteButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    controller.calendarModel.removeAppointment(currentAppointment);
                    JOptionPane.showMessageDialog(inputForm, "Event has been deleted, please press back", "Deleted", JOptionPane.OK_OPTION);
                    Component[] components = inputForm.getComponents();
                    Component[] components2 = dateInputPanel.getComponents();
                    Component[] components3 = endDateInputPanel.getComponents();



                    JTextField t = new JTextField();
                    JComboBox jb = new JComboBox();
                    for (Component c : components) {
                        if (c instanceof JTextField) {
                            t = (JTextField) c;
                            t.setText("");//cleat the fields
                        }
                        if (c instanceof JComboBox) {
                            jb = (JComboBox) c;
                            if (!c.equals(tagsInput)) {
                                jb.setSelectedIndex(0);

                            }

                        }
                    }


                    for (Component c : components2) {

                        if (c instanceof JComboBox) {
                            jb = (JComboBox) c;
                            if (!c.equals(tagsInput)) {
                                jb.setSelectedIndex(0);

                            }

                        }
                    }


                    for (Component c : components3) {

                        if (c instanceof JComboBox) {
                            jb = (JComboBox) c;
                            if (!c.equals(tagsInput)) {
                                jb.setSelectedIndex(0);

                            }

                        }
                    }



                }
            });
        }

    }

    @Override
    public void update() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
